//============================================================================
//  Copyright (c) 1996-2002 Winbond Electronic Corporation
//
//  Module Name:
//    Wb35Rx.c
//
//  Abstract:
//    Processing the Rx message from down layer
//
//============================================================================
#include "sysdef.h"


VOID Wb35Rx_start( IN phw_data_t pHwData )
{
	PWB35RX		pWb35Rx = &pHwData->Wb35Rx;

	// Allow only one thread to run into the Wb35Rx() function
	if( OS_ATOMIC_INC( pHwData->Adapter, &pWb35Rx->RxFireCounter ) == 1 )
	{
		pWb35Rx->EP3vm_state = VM_RUNNING;
		Wb35Rx( pHwData );
	}
	else
		OS_ATOMIC_DEC( pHwData->Adapter, &pWb35Rx->RxFireCounter );
}

// This function cannot reentrain
VOID Wb35Rx( IN phw_data_t pHwData )
{
	PWB35RX		pWb35Rx = &pHwData->Wb35Rx;
	PUCHAR		pRxBufferAddress;
	PURB		pUrb = (PURB)pWb35Rx->RxUrb;
	int			retv;
	ULONG		RxBufferId;


	//
	// Issuing URB
	//
	do
	{
		if( pHwData->SurpriseRemove || pHwData->HwStop )
			break;

		if( pWb35Rx->rx_halt )
			break;

		// Get RxBuffer's ID
		RxBufferId = pWb35Rx->RxBufferId;
		if( !pWb35Rx->RxOwner[ RxBufferId ] )
		{
			// It's impossible to run here.
			#ifdef _PE_RX_DUMP_
			WBDEBUG(("Rx driver fifo unavailable\n"));
			#endif
			FillEventLog(pHwData->Adapter, EVENT_RX_BUFF_UNAVAILABLE);
			break;
		}

		// Update buffer point, then start to bulkin the data from USB
		pWb35Rx->RxBufferId++;
		pWb35Rx->RxBufferId %= MAX_USB_RX_BUFFER_NUMBER;

		pWb35Rx->CurrentRxBufferId = RxBufferId; // 20060331 for complete routine usage

		//pRxBufferAddress = pWb35Rx->RxBuffer[ RxBufferId ];
		//142_o add by anson
		if (OS_MEMORY_ALLOC_OK != OS_MEMORY_ALLOC((PVOID *)&pWb35Rx->pDRx, MAX_USB_RX_BUFFER))
		{
			#ifdef _PE_STATE_DUMP_
			WBDEBUG(("Rx memory alloc failed\n"));
			#endif
			break;
		}
		pRxBufferAddress = pWb35Rx->pDRx;
		

		usb_fill_bulk_urb( pUrb,
					pHwData->WbUsb.udev,
					usb_rcvbulkpipe(pHwData->WbUsb.udev, 3),
					pRxBufferAddress,
					MAX_USB_RX_BUFFER,
					Wb35Rx_Complete,
					pHwData);

		pWb35Rx->EP3vm_state = VM_RUNNING;

		retv = wb_usb_submit_urb( pUrb );

		if( retv != 0 )
		{
			#ifdef _PE_RX_DUMP_
			WBDEBUG(("Rx URB sending error\n"));
			#endif
			break;
		}

		return;

	}while(FALSE);

	// VM stop
	pWb35Rx->EP3vm_state = VM_STOP;
	OS_ATOMIC_DEC( pHwData->Adapter, &pWb35Rx->RxFireCounter );
}
VOID Wb35Rx_Complete( IN PURB pUrb )
{
	phw_data_t	pHwData = pUrb->context;
	PWB35RX		pWb35Rx = &pHwData->Wb35Rx;
	PUCHAR		pRxBufferAddress;
	ULONG		SizeCheck;
	USHORT		BulkLength;
	ULONG		RxBufferId;
	R00_DESCRIPTOR 	R00; //20060926 add by anson's endian

	// Variable setting
	pWb35Rx->EP3vm_state = VM_COMPLETED;
	pWb35Rx->EP3VM_status = pUrb->status;//Store the last result of Irp

	do
	{
		RxBufferId = pWb35Rx->CurrentRxBufferId;
		//142_o add by anson
		//pRxBufferAddress = pWb35Rx->RxBuffer[ RxBufferId ];
		pRxBufferAddress = pWb35Rx->pDRx;
		BulkLength = (USHORT)pUrb->actual_length;

		//The IRP is completed
		pWb35Rx->EP3vm_state = VM_COMPLETED;

		if( pHwData->SurpriseRemove || pHwData->HwStop ) // Must be here, or RxBufferId is invalid
			break;

		if( pWb35Rx->rx_halt )
			break;

		//Start to process the data only in successful condition
		pWb35Rx->RxOwner[ RxBufferId ] = 0; // Set the owner to driver
		//pR00 = (PR00_DESCRIPTOR)pRxBufferAddress;  
		R00.value = le32_to_cpu(*(PULONG)pRxBufferAddress);  //20060926 anson's endian
		//The URB is completed, check the result
		if( pWb35Rx->EP3VM_status != 0 )
		{
			#ifdef _PE_USB_STATE_DUMP_
			WBDEBUG(("EP3 IoCompleteRoutine return error\n"));
			DebugUsbdStatusInformation( pWb35Rx->EP3VM_status );
			#endif
			pWb35Rx->EP3vm_state = VM_STOP;
			break; // Exit while(FALSE);
		}

		// 20060220 For recovering. check if operating in single USB mode
		if( !HAL_USB_MODE_BURST( pHwData ) )
		{
			SizeCheck = R00.R00_receive_byte_count;  //20060926 anson's endian
			if( (SizeCheck & 0x03) > 0 )
				SizeCheck -= 4;
			SizeCheck = (SizeCheck + 3) & ~0x03;
			SizeCheck += 12; // 8 + 4 badbeef
			if( (BulkLength > 1600) || 
				(SizeCheck > 1600) || //1548) )// 1536 + 8 + 4
				(BulkLength != SizeCheck) || 
				(BulkLength == 0) ) // Add for fail Urb
			{
				pWb35Rx->EP3vm_state = VM_STOP;
				pWb35Rx->Ep3ErrorCount2++;
			}
		}

		//Indicating the receiving data
		pWb35Rx->ByteReceived += BulkLength;
		pWb35Rx->RxBufferSize[ RxBufferId ] = BulkLength;


		if( !pWb35Rx->RxOwner[ RxBufferId ])
			Wb35Rx_indicate( pHwData );
		
		OS_MEMORY_FREE( pWb35Rx->pDRx, MAX_USB_RX_BUFFER);
		// Do the next receive
		Wb35Rx( pHwData );

		return;

	}while(FALSE);

	pWb35Rx->RxOwner[ RxBufferId ] = 1; // Set the owner to hardware
	OS_ATOMIC_DEC( pHwData->Adapter, &pWb35Rx->RxFireCounter );
	pWb35Rx->EP3vm_state = VM_STOP;
}

//============================================================================================
BOOLEAN Wb35Rx_initial( IN phw_data_t pHwData )
{
	PWB35RX pWb35Rx = &pHwData->Wb35Rx;

	// Initial the Buffer Queue
	Wb35Rx_reset_descriptor( pHwData );

	pWb35Rx->RxUrb = wb_usb_alloc_urb(0);
	if( !pWb35Rx->RxUrb )
		return FALSE;

	return TRUE;
}

VOID Wb35Rx_stop( IN phw_data_t pHwData )
{
	PWB35RX		pWb35Rx = &pHwData->Wb35Rx;

	// Canceling the Irp if already sends it out.
	if( pWb35Rx->EP3vm_state == VM_RUNNING )
	{
		usb_unlink_urb( pWb35Rx->RxUrb ); // Only use unlink, let Wb35Rx_destrot to free them
		#ifdef _PE_RX_DUMP_
		WBDEBUG(("EP3 Rx stop\n"));
		#endif
	}
}

// Only can be run in passive-level
VOID Wb35Rx_destroy( IN phw_data_t pHwData )
{
	PWB35RX pWb35Rx = &pHwData->Wb35Rx;

	do{
		OS_SLEEP(10000); // Delay for waiting function enter 940623.1.a
	}while( pWb35Rx->EP3vm_state != VM_STOP );
	OS_SLEEP(10000); // Delay for waiting function exit 940623.1.b

	if( pWb35Rx->RxUrb )
		usb_free_urb( pWb35Rx->RxUrb );
	#ifdef _PE_RX_DUMP_
	WBDEBUG(("Wb35Rx_destroy OK\n"));
	#endif
}

VOID Wb35Rx_reset_descriptor( IN phw_data_t pHwData )
{
	PWB35RX pWb35Rx = &pHwData->Wb35Rx;
	ULONG	i;

	pWb35Rx->ByteReceived = 0;
	pWb35Rx->RxProcessIndex = 0;
	pWb35Rx->RxBufferId = 0;
	pWb35Rx->EP3vm_state = VM_STOP;
	pWb35Rx->rx_halt = 0;

	// Initial the Queue. The last buffer is reserved for used if the Rx resource is unavailable.
	for( i=0; i<MAX_USB_RX_BUFFER_NUMBER; i++ )
		pWb35Rx->RxOwner[i] = 1;
}

VOID Wb35Rx_adjust( IN PDESCRIPTOR pRxDes )
{
	PULONG	pRxBufferAddress;
	ULONG	DecryptionMethod;
	ULONG	i;
	USHORT	BufferSize;


	DecryptionMethod = pRxDes->R01.R01_decryption_method;
	pRxBufferAddress = pRxDes->buffer_address[0];
	BufferSize = pRxDes->buffer_size[0];

	// Adjust the last part of data. Only data left
	BufferSize -= 4; // For CRC-32
	if( DecryptionMethod )
		BufferSize -= 4;
	if( DecryptionMethod == 3 ) // For CCMP
		BufferSize -= 4;

	// Adjust the IV field which after 802.11 header and ICV field.
	if( DecryptionMethod == 1 ) // For WEP
	{
		for( i=6; i>0; i-- )
			pRxBufferAddress[i] = pRxBufferAddress[i-1];
		pRxDes->buffer_address[0] = pRxBufferAddress + 1;//Update the descriptor, shift 4 byte
		BufferSize -= 4; // 4 byte for IV
	}
	else if( DecryptionMethod ) // For TKIP and CCMP
	{
		for( i=7; i>1; i-- )
			pRxBufferAddress[i] = pRxBufferAddress[i-2];
		pRxDes->buffer_address[0] = pRxBufferAddress + 2;//Update the descriptor, shift 8 byte
		BufferSize -= 8; // 8 byte for IV + ICV
	}
	pRxDes->buffer_size[0] = BufferSize;
}

//931130.4.b
USHORT Wb35Rx_indicate( IN phw_data_t pHwData )
{
	DESCRIPTOR	RxDes;
//	PWB35REG pWb35Reg = &pHwData->Wb35Reg;
	PWB35RX	pWb35Rx = &pHwData->Wb35Rx;
	PUCHAR		pRxBufferAddress;
	USHORT		PacketSize;
	USHORT		stmp, BufferSize, stmp2 = 0;
	ULONG		RxBufferId;

	// Only one thread be allowed to run into the follow
	do
	{
		RxBufferId = pWb35Rx->RxProcessIndex;
		if( pWb35Rx->RxOwner[ RxBufferId ] )//Owner by VM
			break;

		pWb35Rx->RxProcessIndex++;
		pWb35Rx->RxProcessIndex %= MAX_USB_RX_BUFFER_NUMBER;
		//142_o add by anson
		//pRxBufferAddress = pWb35Rx->RxBuffer[ RxBufferId ];
		pRxBufferAddress = pWb35Rx->pDRx;
		BufferSize = pWb35Rx->RxBufferSize[ RxBufferId ];

		// Parse the bulkin buffer
		while( BufferSize >= 4 )
		{
			if( ( cpu_to_le32(*(PULONG)pRxBufferAddress) & 0x0fffffff) == RX_END_TAG ) //Is ending? 921002.9.a
				break;

			// Get the R00 R01 first
			RxDes.R00.value =le32_to_cpu(*(PULONG)pRxBufferAddress); //20060926 add by anson's endian
			PacketSize = (USHORT)RxDes.R00.R00_receive_byte_count;
			RxDes.R01.value = le32_to_cpu(*((PULONG)(pRxBufferAddress+4))); //20060926 anson's ednian
			// For new DMA 4k
			if( (PacketSize & 0x03) > 0 )
				PacketSize -= 4;

			//Basic check for Rx length. Is length valid?
			if( PacketSize > MAX_PACKET_SIZE )
			{
				#ifdef _PE_RX_DUMP_
				WBDEBUG(("Serious ERROR : Rx data size too long, size =%d\n", PacketSize));
				#endif

				pWb35Rx->EP3vm_state = VM_STOP; 
				pWb35Rx->Ep3ErrorCount2++;
				break;
			}

			// Start to process Rx buffer
//			RxDes.Descriptor_ID = RxBufferId; // Due to synchronous indicate, the field doesn't necessary to use.
			BufferSize -= 8;//subtract 8 byte for 35's USB header length
			pRxBufferAddress += 8;

			RxDes.buffer_address[0] = pRxBufferAddress;
			RxDes.buffer_size[0] = PacketSize;
			RxDes.buffer_number = 1;
			RxDes.buffer_start_index = 0;
			RxDes.buffer_total_size = RxDes.buffer_size[0];
			Wb35Rx_adjust( &RxDes );

			// Indicating to upper module
			hal_descriptor_indicate( pHwData, &RxDes );
			pWb35Rx->LastR1 = RxDes.R01.value;

			// Move RxBuffer point to the next
			stmp = PacketSize + 3;
			stmp &= ~0x03; // 4n alignment
			pRxBufferAddress += stmp;
			BufferSize -= stmp;
			stmp2 += stmp;
		}

		// Reclaim resource
		pWb35Rx->RxOwner[ RxBufferId ] = 1;

	}while(TRUE);

	return stmp2;
}


